<template>
  <div class="table-box">
    <el-card style="margin-bottom: 10px" header="项目信息" class="box-card">
      <el-descriptions :border="true">
        <el-descriptions-item label="项目名称" label-width="150" width="300">{{ selectedRow?.projectName }}</el-descriptions-item>
        <el-descriptions-item label="项目编号" label-width="200">{{ selectedRow?.projectNumber }}</el-descriptions-item>
        <el-descriptions-item label="备注" label-width="100" width="500">{{ selectedRow?.remark }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ selectedRow?.customerName }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ selectedRow?.createDate.toString().replace("T", " ").split(".")[0] }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <ProTable v-if="ready" ref="proTable" :columns="columns" :request-api="queryProjectRecord">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="openInsertDialog">创建项目明细</el-button>
      </template>
      <template #recordNumber="scope">
        <el-button type="primary" link @click="openMediumDialog(scope.row)">{{ scope.row.recordNumber }}</el-button>
      </template>
      <template #createDate="scope">
        {{ scope.row.createDate.replace("T", " ").split(".")[0] }}
      </template>
      <template #updateDate="scope">
        {{ scope.row.updateDate.replace("T", " ").split(".")[0] }}
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="openUpdateDialog(scope.row)"> 编辑 </el-button>
        <el-button type="primary" link :icon="EditPen" @click="commitInfo(scope.row)" v-if="scope.row.projectRecordStatus === 0">
          提交
        </el-button>
      </template>
    </ProTable>
    <!-- 新增对话框 -->
    <el-dialog width="30%" title="创建项目明细记录" v-model="insertDialogVisible">
      <el-form ref="insertFormRef" :model="insertParam" :rules="ruleForm" label-width="150px" class="demo-ruleForm">
        <el-form-item label="明细记录名称" prop="recordName">
          <el-input v-model="insertParam.recordName"></el-input>
        </el-form-item>

        <el-form-item label="记录类型" prop="recordType">
          <el-select v-model="insertParam.recordType">
            <el-option label="普通" :value="1" />
            <el-option label="重要" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="总金额" prop="totalAmount">
          <el-input-number v-model="insertParam.totalAmount"></el-input-number>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="insertParam.remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="insertDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addCustomerProjectRecord(insertFormRef)">创建</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog width="30%" title="修改项目明细记录" v-model="updateDialogVisible">
      <el-form ref="updateFormRef" :model="updateParam" :rules="ruleForm" label-width="150px" class="demo-ruleForm">
        <el-form-item label="明细记录名称" prop="recordName">
          <el-input v-model="updateParam.recordName"></el-input>
        </el-form-item>

        <el-form-item label="记录类型" prop="recordType">
          <el-select v-model="updateParam.recordType">
            <el-option label="普通" :value="1" />
            <el-option label="重要" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="总金额" prop="totalAmount">
          <el-input-number v-model="updateParam.totalAmount"></el-input-number>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="updateParam.remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateCustomerProjectRecord(updateFormRef)"> 修改</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog width="50%" title="媒介填报记录明细" v-model="mediumDialogVisible">
      <div class="table-box" style="height: 550px">
        <ProTable
          v-if="mediumDialogVisible"
          ref="mediumProTable"
          :columns="mediumColumns"
          :request-api="queryMediumByProjectRecord"
        >
          <template #createDate="scope">
            {{ scope.row.createDate.replace("T", " ").split(".")[0] }}
          </template>
          <template #publishDate="scope">
            {{ scope.row.publishDate.replace("T", " ").split(".")[0] }}
          </template>
        </ProTable>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts" name="projectRecord">
import { ref, reactive, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  CirclePlus,
  Delete,
  EditPen,
  Download,
  Upload,
  View,
  Refresh,
  ElementPlus,
  More,
  Picture
} from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import ProTable from "@/components/ProTable/index.vue";
import UploadImg from "@/components/Upload/Img.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { HxCustomers } from "@/api/interface/customers";
import { queryCustomers } from "@/api/modules/customers";

import { CreateCustomerProjectParam, CustomerProjectResult, EditCustomerProjectInfoParam } from "@/api/interface/customerProject";
import {
  createCustomerProject,
  editCustomerProjectInfo,
  editCustomerProjectStatus,
  findCustomerProjectInfo,
  queryMyCustomerProjectList
} from "@/api/modules/customerProject";
import {
  customerProjectStatusEnum,
  projectRecordStatusEnum,
  projectRecordTypeEnum,
  publishStateEnum,
  publishTypeEnum,
  statusFieldNames
} from "@/enums/httpEnum";
import { useRoute } from "vue-router";
import {
  createProjectRecord,
  editProjectREcordInfo,
  editProjectRecordStatus,
  queryProjectAllRecord
} from "@/api/modules/projectRecord";
import { CreateProjectRecordParam, EditProjectRecordInfoParam, HxCustomerProjectRecord } from "@/api/interface/projectRecord";
import { HxMediumRecord } from "@/api/interface/mediumRecord";
import { queryProjectRecordAllMediumRecords } from "@/api/modules/mediumRecord";

const route = useRoute();

const ready = ref(false);

onMounted(async () => {
  const param = route.query.customerProjectId as string;
  if (param) {
    selectedRow.value = (await findCustomerProjectInfo({ projectId: param })).data;
    proTable.value?.getTableList();
  } else {
    ElMessage.error("未查询到项目信息，请重试");
  }
  ready.value = true;
});

let selectedRow = ref<CustomerProjectResult>();

const proTable = ref<ProTableInstance>();

const queryProjectRecord = (params: any) => {
  let requestParam = JSON.parse(JSON.stringify(params));
  requestParam.SourceCustomersProjectId = selectedRow.value?.projectId;
  return queryProjectAllRecord(requestParam);
};

/** 新增对话框是否可见 */
const insertDialogVisible = ref(false);

/** 修改对话框是否可见 */
const updateDialogVisible = ref(false);

/** 新增表单Form */
const insertFormRef = ref<FormInstance>();

/** 修改表单Form */
const updateFormRef = ref<FormInstance>();

/** 新增初始化参数 */
const initInsertParam = {
  sourceCustomersProjectId: "",
  recordName: "",
  recordType: 1,
  totalAmount: 0
};

/** 新增参数 */
const insertParam = reactive<CreateProjectRecordParam>({
  sourceCustomersProjectId: "",
  recordName: "",
  recordType: 1,
  remark: "",
  totalAmount: 0
});

/** 修改参数 */
const updateParam = reactive<EditProjectRecordInfoParam>({
  projectRecordId: "",
  projectRecordStatus: 1,
  sourceCustomersProjectId: "",
  recordName: "",
  recordType: 1,
  remark: "",
  totalAmount: 0
});

/** 客户列表 */
let customers = ref<HxCustomers[]>([]);

/** form表单验证规则 */
const ruleForm = reactive<FormRules>({
  recordName: [{ required: true, message: "请输入明细记录名称", trigger: "change" }],
  totalAmount: [{ required: true, message: "请输入明细金额", trigger: "change" }],
  recordType: [{ required: true, message: "请选择明细记录类型", trigger: "change" }]
});

/** 表格配置项 */
const columns = reactive<ColumnProps<HxCustomerProjectRecord>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { type: "index", label: "", width: 80 },
  {
    prop: "recordName",
    label: "明细记录名称",
    width: 150,
    search: { el: "input", tooltip: "请输入明细记录名称" }
  },
  {
    prop: "recordNumber",
    label: "明细记录编码",
    width: 200,
    search: { el: "input", tooltip: "请输入明细记录编码" }
  },

  {
    prop: "recordType",
    label: "明细记录类别",
    width: 150,
    tag: true,
    enum: projectRecordTypeEnum,
    search: { el: "select", props: { filterable: true } },
    fieldNames: statusFieldNames
  },
  {
    prop: "projectRecordStatus",
    label: "明细记录状态",
    width: 150,
    tag: true,
    enum: projectRecordStatusEnum,
    search: { el: "select", props: { filterable: true } },
    fieldNames: statusFieldNames
  },
  {
    prop: "totalAmount",
    label: "总金额",
    width: 150
  },
  {
    prop: "createDate",
    label: "创建时间",
    width: 200
  },
  {
    prop: "createUser",
    label: "创建人",
    width: 120
  },
  {
    prop: "remark",
    label: "备注",
    width: 300
  },
  { prop: "operation", label: "操作", fixed: "right", width: 200 }
]);

/** 打开新增对话框 */
const openInsertDialog = async () => {
  if (!selectedRow.value) {
    ElMessage.error("未查询到项目信息，请重试");
    return;
  }
  insertDialogVisible.value = true;
  insertParam.sourceCustomersProjectId = selectedRow.value.projectId;
};

/** 打开修改对话框 */
const openUpdateDialog = async (param: CustomerProjectResult) => {
  updateDialogVisible.value = true;
  Object.assign(updateParam, param);
};

/** 新增项目明细记录*/
const addCustomerProjectRecord = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await createProjectRecord(insertParam);
      ElMessage.success("创建项目明细记录成功");
      insertDialogVisible.value = false;
      Object.assign(insertParam, initInsertParam);
      proTable.value?.getTableList();
    } else {
      ElMessage.error("请填入必填数据");
    }
  });
};

/** 修改订单 */
const updateCustomerProjectRecord = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await editProjectREcordInfo(updateParam);
      ElMessage.success("修改项目明细记录成功");
      updateDialogVisible.value = false;
      Object.assign(insertParam, initInsertParam);
      proTable.value?.getTableList();
    } else {
      ElMessage.error("请填入必填数据");
    }
  });
};

const commitInfo = async (param: HxCustomerProjectRecord) => {
  ElMessageBox.confirm("是否提交记录?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    await editProjectRecordStatus({ projectRecordId: param.projectRecordId, projectRecordStatus: 1 });
    ElMessage.success("提交成功");
    proTable?.value?.getTableList();
  });
};

const mediumDialogVisible = ref(false);

const mediumProTable = ref<ProTableInstance>();

/** 表格配置项 */
const mediumColumns = reactive<ColumnProps<HxMediumRecord>[]>([
  { type: "index", label: "", width: 80 },
  {
    prop: "mediumRecordName",
    label: "媒介记录名称",
    width: 150
  },
  {
    prop: "publishType",
    label: "发布类型",
    width: 200,
    tag: true,
    enum: publishTypeEnum,
    fieldNames: statusFieldNames
  },

  {
    prop: "publishState",
    label: "发布状态",
    width: 150,
    tag: true,
    enum: publishStateEnum,
    fieldNames: statusFieldNames
  },
  {
    prop: "publishPlatform",
    label: "发布平台",
    width: 150,
    tag: true
  },
  {
    prop: "publishDate",
    label: "发布时间",
    width: 150
  },
  {
    prop: "createDate",
    label: "创建时间",
    width: 200
  },
  {
    prop: "createUser",
    label: "创建人",
    width: 120
  }
]);

let selectProjectRecord = ref<HxCustomerProjectRecord>();

const openMediumDialog = (param: HxCustomerProjectRecord) => {
  mediumDialogVisible.value = true;
  selectProjectRecord.value = param;
};

const queryMediumByProjectRecord = (param: any) => {
  let newParams = JSON.parse(JSON.stringify(param));
  newParams.sourceProjectRecordNumber = selectProjectRecord.value?.recordNumber;

  return queryProjectRecordAllMediumRecords(newParams);
};
</script>
